#include "RenderPixelObject.h"

#include "Containers/Map.h"
#include "PreRenderPixelObject.h"
#include "RenderPixelObjectMap.h"
#include "PreRenderPixelObjectMap.h"
#include "Render/PreRenderContext.h"

void CRenderPixelObjectInstanceGroup::GeneratePreRenderData(SPreRenderContext & InPreRenderContext, std::shared_ptr<CPreRenderPixelObjectGroup> OutData) const
{
    {
        TMap<std::shared_ptr<CRenderMesh>
            , std::shared_ptr<CPreRenderPixelObjectMesh>> MeshMap;

        for(auto& Instance:Instances)
        {
            auto Mesh=Instance->Mesh;
            if(!MeshMap.Contains(Mesh))
            {
                auto PreRenderMesh=std::make_shared<CPreRenderPixelObjectMesh>();
                PreRenderMesh->Mesh=InPreRenderContext.PreRender(Mesh);
                PreRenderMesh->ObjectIDs.Add(Instance->ObjectID);
                PreRenderMesh->ModelMatrices.Add(Instance->ModelMatrix);
                MeshMap.Add(Mesh,PreRenderMesh);
            }
            else
            {
                auto PreRenderMesh=MeshMap[Mesh];
                PreRenderMesh->ObjectIDs.Add(Instance->ObjectID);
                PreRenderMesh->ModelMatrices.Add(Instance->ModelMatrix);
            }
        }

        for(auto& MeshPair:MeshMap)
        {
            OutData->Meshs.Add(MeshPair.Value);
        }
    }

    {
        TMap<std::shared_ptr<CRenderMesh>
            , std::shared_ptr<CPreRenderPixelObjectMesh>> MeshMap;

        for(auto& Instance:ForegroundInstances)
        {
            auto Mesh=Instance->Mesh;
            if(!MeshMap.Contains(Mesh))
            {
                auto PreRenderMesh=std::make_shared<CPreRenderPixelObjectMesh>();
                PreRenderMesh->Mesh=InPreRenderContext.PreRender(Mesh);
                PreRenderMesh->ObjectIDs.Add(Instance->ObjectID);
                PreRenderMesh->ModelMatrices.Add(Instance->ModelMatrix);
                MeshMap.Add(Mesh,PreRenderMesh);
            }
            else
            {
                auto PreRenderMesh=MeshMap[Mesh];
                PreRenderMesh->ObjectIDs.Add(Instance->ObjectID);
                PreRenderMesh->ModelMatrices.Add(Instance->ModelMatrix);
            }
        }

        for(auto& MeshPair:MeshMap)
        {
            OutData->ForegroundMeshs.Add(MeshPair.Value);
        }
    }

    OutData->PixelObjectMap=std::make_shared<CPreRenderPixelObjectMap>();
    OutData->PixelObjectMap->ID=PixelObjectMap->ID;
    OutData->MapWidth=MapWidth;
    OutData->MapHeight=MapHeight;
}